package ae.pcfc.etks.online.web.controller.user.general.person;

/* $Id: UserPersonController 
 * Copyright (C) 2011, Trakhees
 *  
 *  History
 *
 * Date  			Author 					Remarks
 * -------------------------------------------------------------
 * April 13, 2011 	Neha_Chauhan 	        Created
 *
 */
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.util.WebUtils;

import ae.pcfc.etks.online.common.delegate.ClientRegistrationDelegate;
import ae.pcfc.etks.online.common.delegate.SecretQuestionDelegate;
import ae.pcfc.etks.online.common.delegate.UserDelegate;
import ae.pcfc.etks.online.common.vo.ClientPersonVO;
import ae.pcfc.etks.online.common.vo.LabelVO;
import ae.pcfc.etks.online.common.vo.NonClientPersonVO;
import ae.pcfc.etks.online.common.vo.SCPersonVO;
import ae.pcfc.etks.online.common.vo.SecretQuestionVO;
import ae.pcfc.etks.online.common.vo.UserVO;
import ae.pcfc.etks.online.web.ConstantsAdmin;
import ae.pcfc.etks.online.web.ViewPath;
import ae.pcfc.etks.online.web.ViewUtils;
import ae.pcfc.etks.online.web.controller.BaseController;
import ae.pcfc.etks.online.web.model.UserModel;
import ae.pcfc.etks.online.web.util.SecurityUtils;

/**
 * Controller that handles all {@link UserPersonController}-related requests,
 * i.e.: all requests for /user/general/person/*
 * 
 * @author Neha Chauhan
 */

@Controller
@RequestMapping(ViewPath.USER_PERSON)
public class UserPersonController extends BaseController {

	private UserDelegate userDelegate;

	@Resource(name = "userDelegate")
	public void setUserDelegate(UserDelegate userDelegate) {
		this.userDelegate = userDelegate;
	}

	private ClientRegistrationDelegate clientRegistrationDelegate;

	@Resource(name = "clientRegistrationDelegate")
	public void setClientRegistrationDelegate(
			ClientRegistrationDelegate clientRegistrationDelegate) {
		this.clientRegistrationDelegate = clientRegistrationDelegate;
	}

	private SecretQuestionDelegate secretQuestionDelegate;

	@Resource(name = "secretQuestionDelegate")
	public void setSecretQuestionDelegate(
			SecretQuestionDelegate secretQuestionDelegate) {
		this.secretQuestionDelegate = secretQuestionDelegate;
	}

	@ModelAttribute(value = ConstantsAdmin.USER_PERSON_REGISTRATION_INFM_REQUEST_MODEL_KEY)
	public NonClientPersonVO populateUserInfoEdit(HttpServletRequest request,
			@RequestParam(value = "id", required = false) String id) {

		// TODO Here we'll place the logic to load the User Data through an Id
		return new NonClientPersonVO();

	}

	@ModelAttribute(ConstantsAdmin.USER_SECRETQUESTION_REQUEST_MODEL_KEY)
	public List<LabelVO> populateSecretQuestionList() {

		List<LabelVO> labelList = new ArrayList<LabelVO>();

		LabelVO labelVO;
		List<SecretQuestionVO> secretQuestionVOs = secretQuestionDelegate
				.getSecretQuestionList();

		for (SecretQuestionVO secretQuestionVO : secretQuestionVOs) {
			labelVO = getMapper().map(secretQuestionVO, LabelVO.class);
			labelList.add(labelVO);

		}
		return labelList;
	}

	/**
	 * Custom handler for displaying the form, i.e.: GET requests for
	 * /user/general/person/
	 * 
	 * @see WEB-INF/jsp/user/general/person/edit.jsp
	 */

	@RequestMapping(value = "/edit.htm", method = RequestMethod.GET)
	public void form(
			@RequestParam(value = "clientId", required = true) String id,
			@ModelAttribute(value = ConstantsAdmin.USER_PERSON_EDIT_INFO_REQUEST_MODEL_KEY) UserModel command) {

	}

	@ModelAttribute(ConstantsAdmin.USER_PERSON_EDIT_INFO_REQUEST_MODEL_KEY)
	public UserModel populateUserInfo(HttpServletRequest request,
			@RequestParam(value = "id", required = false) String id) {

		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		String strUserName = null;

		if (principal instanceof UserDetails) {
			strUserName = ((UserDetails) principal).getUsername();
		} else {
			strUserName = principal.toString();
		}

		ClientPersonVO clientPersonVO = this.clientRegistrationDelegate
				.findClientPersonByUserName(strUserName);

		if (clientPersonVO != null) {

			UserModel clientPersonRegister = new UserModel();
			UserVO userVO = null;

			if (clientPersonVO.getUserVOs() != null
					&& clientPersonVO.getUserVOs().size() > 0)
				userVO = clientPersonVO.getUserVOs().get(0);

			if (userVO != null) {
				getMapper().map(userVO, clientPersonRegister);
				return clientPersonRegister;
			}
		}
		return new UserModel();
	}

	@ModelAttribute(value = ConstantsAdmin.CLIENT_PERSON_REGISTER_SUMMARY_REQUEST_MODEL_KEY)
	public SCPersonVO populateReferenceData(HttpServletRequest request,
			@RequestParam(value = "clientId", required = false) String clientId) {

		String trakheesId = SecurityUtils.decrypt(clientId);

		SCPersonVO scPersonVO = clientRegistrationDelegate
				.findSCPersonByTrakheesId(trakheesId);

		if (scPersonVO == null)
			scPersonVO = new SCPersonVO();

		return scPersonVO;

	}

	/**
	 * Custom handler for displaying the form, i.e.:POST requests for
	 * /user/general/person/edit.jsp
	 * 
	 * @see #form(UserCompanyInfoEdit)
	 * @see WEB-INF/jsp/user/general/person/edit.jsp
	 */

	@RequestMapping(method = RequestMethod.POST, value = "/edit.htm")
	public String form(
			HttpServletRequest request,
			SessionStatus status,
			@ModelAttribute(value = ConstantsAdmin.USER_PERSON_EDIT_INFO_REQUEST_MODEL_KEY) @Valid UserModel userPersonEditInfo,
			BindingResult errors) {

		boolean isSave = WebUtils.hasSubmitParameter(request,
				ConstantsAdmin.SAVE_BUTTON);

		if (isSave) {
			if (errors.hasErrors()) {

				return ViewUtils.DEFAULT_VIEW;

			} else {

				ClientPersonVO personClientVO = new ClientPersonVO();

				if (personClientVO != null) {
					getMapper().map(userPersonEditInfo, personClientVO);

					UserVO userVO = new UserVO();

					getMapper().map(userPersonEditInfo, userVO);
					userVO.setStrPassword(SecurityUtils
							.hashPassword(userPersonEditInfo.getStrPassword()));

					if (userVO.getStrEmailNotification() == null
							|| userVO.getStrEmailNotification().equals(""))
						userVO.setStrEmailNotification("N");
					if (userVO.getStrSmsNotification() == null
							|| userVO.getStrSmsNotification().equals(""))
						userVO.setStrSmsNotification("N");

					this.clientRegistrationDelegate.updateClientPerson(userVO);

					// String[] messageArgs = new String[] {
					// messageSource.getMessage("success.user.info.edit", null,
					// RequestContextUtils.getLocale(request)) };
					request.setAttribute(
							ConstantsAdmin.SUCCESS_PARAM,
							getMessageSource().getMessage(
									"success.user.info.edit", null,
									RequestContextUtils.getLocale(request)));
				}
			}

		}
		return ViewUtils.DEFAULT_VIEW;
	}

}
